from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By

from .antd_page_element import AntdPageElement
from ...common.element_function import ElementFunction
from ...exception.TestException import TestException
from ...exception.errorcode import ErrorCode


class Table(AntdPageElement):
    def select(self, title, value):

        row_index=self.checkValue(title, value)

        xpath = './/tbody/tr[{0}]/td[1]'.format(row_index)
        element_value = self.table_element.find_element(By.XPATH, xpath)
        ElementFunction(self._driver).click(element_value)

    def checkValue(self, title, value):
        self.wait_element_presence()
        self.table_element = self._find_table_element()
        title_index = self._find_title_index(title)
        row_index = self._find_col_value_index(title_index, value)
        if row_index < 0:
            raise TestException.by_error_code(ErrorCode.GRID_VALUE_NOT_FIND, value=value, label=title)
        return row_index

    def _find_col_value_index(self, title_index, value):
        row_index = 1
        while True:
            xpath = './/tbody/tr[{0}]/td[{1}]'.format(row_index, title_index)
            try:
                element = self.table_element.find_element(By.XPATH, xpath)
                element_value = element.text.strip()
                if value == element_value:
                    return row_index
            except NoSuchElementException:
                return -1
            row_index += 1

    def _find_title_index(self, title):
        if isinstance(title, int):
            return title
        if not isinstance(title, str):
            raise TestException.by_error_code(ErrorCode.PARAM_ERROR, message="The table title must be int or string")
        if title.isdigit():
            return int(title)
        xpath= './/thead/tr/th'
        element_titles = self.table_element.find_elements(By.XPATH, xpath)

        for index, element in enumerate(element_titles):
            value = element.text.strip()
            if value == title:
                return index + 1
        else:
            raise TestException.by_error_code(ErrorCode.GRID_COLUMN_LABEL_NOT_FIND, value=title)

    def _find_table_element(self):
        xpath = './/table'
        element = self._get_web_element();
        if element.tag_name == 'table':
            return element
        return element.find_element(By.XPATH, xpath);

    def get_identification(self):
        # TODO: 跟据这个来判断不太妥
        # identification = {'class': ['ant-table']}
        id = {'tag': ['table']}
        return id
